package cn.edu.ncut.cs.springboot.petmanagementsystem.service.Impl;

import cn.edu.ncut.cs.springboot.petmanagementsystem.mapper.ShoppingCartMapper;
import cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.ShoppingCart;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.CartService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private ShoppingCartMapper cartMapper;

    @Override
    @Transactional(rollbackOn = Exception.class)
    public boolean addToCart(ShoppingCart cart) {
        if (cart == null || cart.getUserId() == null || cart.getProductId() == null) {
            throw new IllegalArgumentException("参数不完整");
        }

        // 检查是否已存在相同商品
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, cart.getUserId())
                .eq(ShoppingCart::getProductId, cart.getProductId())
                .eq(ShoppingCart::getProductType, cart.getProductType());
        
        ShoppingCart existCart = cartMapper.selectOne(wrapper);
        
        if (existCart != null) {
            // 更新数量
            existCart.setQuantity(existCart.getQuantity() + (cart.getQuantity() == null ? 1 : cart.getQuantity()));
            existCart.setUpdateTime(LocalDateTime.now());
            cartMapper.updateById(existCart);
        } else {
            // 新增
            cart.setQuantity(cart.getQuantity() == null ? 1 : cart.getQuantity());
            cart.setSelected(cart.getSelected() == null ? true : cart.getSelected());
            cart.setCreateTime(LocalDateTime.now());
            cart.setUpdateTime(LocalDateTime.now());
            cartMapper.insert(cart);
        }

        return true;
    }

    @Override
    public List<ShoppingCart> getCartList(Long userId) {
        if (userId == null) {
            return List.of();
        }

        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        wrapper.orderByDesc(ShoppingCart::getCreateTime);
        return cartMapper.selectList(wrapper);
    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public boolean removeFromCart(Long id, Long userId) {
        if (id == null || userId == null) {
            return false;
        }

        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getId, id)
                .eq(ShoppingCart::getUserId, userId);
        
        int result = cartMapper.delete(wrapper);
        return result > 0;
    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public boolean updateCartItemQuantity(Long id, Long userId, Integer quantity) {
        if (id == null || userId == null || quantity == null || quantity <= 0) {
            throw new IllegalArgumentException("参数不完整或数量无效");
        }

        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getId, id)
                .eq(ShoppingCart::getUserId, userId);
        
        ShoppingCart cart = cartMapper.selectOne(wrapper);
        if (cart == null) {
            throw new IllegalArgumentException("购物车项不存在");
        }

        cart.setQuantity(quantity);
        cart.setUpdateTime(LocalDateTime.now());
        int result = cartMapper.updateById(cart);
        return result > 0;
    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public boolean clearCart(Long userId) {
        if (userId == null) {
            return false;
        }

        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        
        int result = cartMapper.delete(wrapper);
        log.info("清空购物车，用户ID: {}, 删除数量: {}", userId, result);
        return true;
    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public boolean batchAddToCart(List<ShoppingCart> cartItems, Long userId) {
        if (cartItems == null || cartItems.isEmpty() || userId == null) {
            throw new IllegalArgumentException("参数不完整");
        }

        try {
            for (ShoppingCart cart : cartItems) {
                cart.setUserId(userId);
                addToCart(cart);
            }
            return true;
        } catch (Exception e) {
            log.error("批量添加购物车失败，用户ID: {}", userId, e);
            throw new RuntimeException("批量添加失败", e);
        }
    }

    @Override
    public Integer getCartCount(Long userId) {
        if (userId == null) {
            return 0;
        }

        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        
        List<ShoppingCart> cartList = cartMapper.selectList(wrapper);
        return cartList.stream()
                .mapToInt(cart -> cart.getQuantity() == null ? 0 : cart.getQuantity())
                .sum();
    }
}
